package com.wenx.study;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * frok/join尝试
 * Created by Think on 2018/11/25.
 */
public class CountTask extends RecursiveTask<Integer> {

    //阈值
    private static final int threshold = 2;

    private int start;

    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end-start) <= threshold;
        //满足条件，执行任务
        if(canCompute){
            for(int i=start;i<=end;i++){
                sum += i;
            }
        }else {
            //继续分割任务
            int middle = (end+start)/2;
            CountTask leftCountTask = new CountTask(start,middle);
            CountTask rightCountTask = new CountTask(middle+1,end);

            //执行子任务
            //leftCountTask.fork();
            //rightCountTask.fork();
            //或者
            invokeAll(leftCountTask,rightCountTask);

            //等待任务执行结束合并结果
            int leftSum = leftCountTask.join();
            int rightSum = rightCountTask.join();

            //合并子任务
            sum = leftSum+rightSum;

        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //调用
        CountTask countTask = new CountTask(1,4);
        ForkJoinTask<Integer> sumTask = forkJoinPool.submit(countTask);

        System.out.println("sumTask = " + sumTask.get());

    }
}
